import React from 'react'
import {
  observer,
  inject,
} from 'mobx-react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import queryString from 'query-string'
import Tab from '@material-ui/core/Tab'
import Tabs from '@material-ui/core/Tabs'
import List from '@material-ui/core/List'
import green from '@material-ui/core/colors/green'
import CircularProgress from '@material-ui/core/CircularProgress'
import Container from '../layout/container'
import TopicListItem from './list-item'
import { tabs } from '../../utils/variable-define'

@inject((stores) => {
  return {
    appState: stores.appState,
    topicStore: stores.topicStore,
  }
}) @observer
export default class TopicList extends React.Component {
  static contextTypes = { // 获取路由的 router 对象
    router: PropTypes.object, // router 是在使用 react-router 的时候会加到 context 里面的
  } // 在组件里就可以使用 context.router

  constructor() {
    super()
    this.changeTab = this.changeTab.bind(this)
    this.listItemClick = this.listItemClick.bind(this)
  }

  componentDidMount() {
    const tab = this.getTab() // 获取 tab
    this.props.topicStore.fetchTopics(tab) // 获取对应tab标签下的数据
  }

  componentWillReceiveProps(nextProps) {
    // 切换 tab 标签组件刷新，有新的nextProps进来对比Props有没有变化
    if (nextProps.location.search !== this.props.location.search) {
      // 不等于，主动获取新的数据
      this.props.topicStore.fetchTopics(this.getTab(nextProps.location.search))
    }
  }

  getTab(params) {
    const search = params || this.props.location.search
    // react-router 里query是不自动转换的 search就是问号后所有参数
    const query = queryString.parse(search)
    return query.tab || 'all' // 通过 localhost:8888/list?tab=xxx 拿到 tab，就可以替换Tabs里的 tabIndex
  }

  bootstrap() {
    return new Promise((resolve) => { // 只需要 resolve 就可以，因为不会出现错误的内容
      setTimeout(() => {
        this.props.appState.count = 3
        resolve(true) // 根据 true 来判断这个方法是否执行成功
      })
    })
  }

  changeTab(event, value) {
    // 路由跳转,需要使用路由的 router 对象
    this.context.router.history.push({
      pathname: '/list',
      search: `?tab=${value}`,
    })
  }

  listItemClick(topic) {
    this.context.router.history.push(`/detail/${topic.id}`)
  }

  render() {
    const {
      topicStore,
    } = this.props
    const topicList = topicStore.topics // 获取 topics
    const { createdTopics } = topicStore // 自己创建的话题
    const { syncingTopics } = topicStore // 正在异步获取数据
    const { user } = this.props.appState
    const tab = this.getTab()

    return (
      <Container>
        <Helmet>
          <title>This is topic-list</title>
          <meta name="description" content="This is description" />
        </Helmet>
        <Tabs value={tab} onChange={this.changeTab}>
          {
            Object.keys(tabs).map(t => (
              <Tab key={t} label={tabs[t]} value={t} />
            ))
          }
        </Tabs>
        {
          createdTopics && createdTopics.length > 0
            ? (
              <List style={{ backgroundColor: '#dfdfdf' }}>
                {
                  createdTopics.map((topic) => {
                    topic = Object.assign({}, topic, { // eslint-disable-line
                      author: user.info,
                    })
                    return (
                      <TopicListItem
                        key={topic.id}
                        onClick={() => this.listItemClick(topic)} // 传入 topic 形成闭包
                        topic={topic}
                      />
                    )
                  })
                }
              </List>) : null
        }
        <List>
          {
            topicList.map(topic => (
              <TopicListItem
                key={topic.id}
                onClick={() => this.listItemClick(topic)} // 传入 topic 形成闭包
                topic={topic}
              />
            ))
          }
        </List>
        {
          syncingTopics
            ? (
              <div style={{
                display: 'flex',
                justifyContent: 'space-around',
                padding: '40px 0',
              }}
              >
                <CircularProgress style={{ color: green[500] }} size={100} />
              </div>
            )
            : null
        }
      </Container>
    )
  }
}

TopicList.wrappedComponent.propTypes = { // 验证 mobx 注入内容
  appState: PropTypes.object.isRequired,
  topicStore: PropTypes.object.isRequired,
}

TopicList.propTypes = {
  location: PropTypes.object.isRequired,
} // location 对象是 react-router 在渲染组件时默认传入的，所以可以直接使用
